import time

import paho.mqtt.client as mqtt
import json

client_id = '234'
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id=client_id)

connectFlag = False


def on_connect(mqtclient, userdata, flags, rc):
    """连接成功回调函数"""
    # 打印连接结果，0 表示成功，其他值表示失败
    print("connect ", rc)
    global connectFlag
    connectFlag = True

    connSuccssInfo = {
        "type": "connect", "clientId": "test001"
    }
    client.publish("topic/webrobot", json.dumps(connSuccssInfo), qos=1)


def publish():
    global connectFlag
    while not connectFlag:
        time.sleep(0.5)

    time.sleep(1)
    agentCommand = {
        "type": "command",
        "data": [
            {"action": "打开", "object": "https://www.baidu.com"}
        ]
    }
    client.publish("topic/webrobot", json.dumps(agentCommand), qos=1)


if __name__ == "__main__":
    client.on_connect = on_connect
    broker_address = "test.mosquitto.org"
    broker_address = "39.98.199.68"
    client.connect(broker_address, port=1883)
    client.loop_start()
    publish()
    client.loop(5000)
    client.disconnect()

# 发布消息
